﻿using System.ComponentModel.Composition.Hosting;
using System.ComponentModel.Composition.Primitives;
using System.IO;
using System.Reflection;

namespace Songhay.Composition
{
    /// <summary>
    /// Static members for MEF Composition.
    /// </summary>
    public static partial class CompositionUtility
    {
        /// <summary>
        /// Gets the MEF directory catalog of exports.
        /// </summary>
        /// <param name="pathToDirectory">The path to directory.</param>
        /// <returns>Returns <see cref="System.ComponentModel.Composition.Hosting.DirectoryCatalog"/>.</returns>
        public static DirectoryCatalog GetDirectoryCatalog(string pathToDirectory)
        {
            return new DirectoryCatalog(pathToDirectory);
        }

        /// <summary>
        /// Gets the MEF directory catalog of exports from the parent folder
        /// of the specified <see cref="System.Reflection.Assembly"/>.
        /// </summary>
        /// <param name="dll">The DLL.</param>
        /// <returns>
        /// Returns <see cref="System.ComponentModel.Composition.Hosting.DirectoryCatalog"/>.
        /// </returns>
        public static DirectoryCatalog GetDirectoryCatalog(Assembly dll)
        {
            if(dll == null) return null;
            var pathToDirectory = Path.GetDirectoryName(dll.Location);
            return new DirectoryCatalog(pathToDirectory);
        }

        /// <summary>
        /// Gets the MEF directory or assembly catalog of exports.
        /// </summary>
        /// <param name="path">The path.</param>
        public static ComposablePartCatalog GetDirectoryOrAssemblyCatalog(string path)
        {
            if(Directory.Exists(path))
            {
                var directoryCatalog = CompositionUtility.GetDirectoryCatalog(path);
                return directoryCatalog;
            }
            else if(File.Exists(path))
            {
                var dll = Assembly.LoadFile(path);
                var assemblyCatalog = new AssemblyCatalog(dll);
                return assemblyCatalog;
            }
            return null;
        }
    }
}
